package com.hanlp.top_interview_150.数组;

import java.util.Arrays;

/**
 * 88. 合并两个有序数组
 * https://leetcode.cn/problems/merge-sorted-array/description/?envType=study-plan-v2&envId=top-interview-150
 */
public class A01 {
    public static void main(String[] args) {
        int[] nums1 = {1,2,3,0,0,0};
        int[] nums2 = {2,5,6};
        merge(nums1,3,nums2,3);
    }
    public static void merge(int[] nums1, int m, int[] nums2, int n) {
        int i = 0,j=0;
        int[] merge = new int[m+n];
        for (int k = 0; k < m + n; k++) {
            if(i>=m){
                for (int l = j; l < n; l++) {
                    merge[i+j] = nums2[j];
                    j++;
                }
                copy(merge,nums1);
                //System.out.println(Arrays.toString(merge).replace(" ",""));
                return;
            } else if (j>=n) {
                for (int l = i; l < m; l++) {
                    merge[i+j] = nums1[i];
                    i++;
                }
                copy(merge,nums1);
                //System.out.println(Arrays.toString(merge).replace(" ",""));
                return;
            } else {
                if(nums1[i] <= nums2[j]){
                    merge[i+j] = nums1[i];
                    i++;
                }else {
                    merge[i+j] = nums2[j];
                    j++;
                }
            }

        }
        copy(merge,nums1);
        //System.out.println(Arrays.toString(merge).replace(" ",""));
    }

    public static void copy(int[] form,int[] to){
        for (int i = 0; i < form.length; i++) {
            to[i] = form[i];
        }
    }
}
